import rpy2.robjects as ro
from rpy2.robjects.packages import importr
from rpy2.robjects import FloatVector
#from rpy2.robjects.vectors import DataFrame

import numpy as np
import csv
from datetime import datetime
from time import strftime
import matplotlib.pyplot as plt
import math



def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV, datatype="int"):
    sKey = []
    fn = inputCSV
    f = open(inputCSV)
    #ra = csv.DictReader(file(fn), dialect="excel")
    ra = csv.DictReader(f, dialect="excel")

    if datatype=="int":
        for record in ra:
            #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
            for item in ra.fieldnames:
                temp = int(float(record[item]))
                sKey.append(temp)
    elif datatype=="float":
        for record in ra:
            for item in ra.fieldnames:
                temp = float(record[item])
                sKey.append(temp)
    else:
        print 'incorrect value in second parameter (datatype)'
        return


    sKey = np.array(sKey)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey

def pwreg_R(resp, pred, changept.predname, changept.choices):
    # piecewise regression using r library
    for i in range(len(changept.choices)-1):
        x2star = (predictor - changept.choices[i]) * np.greater(predictor, changept.choices[i])
        fit = stats.lm('resp ~ pred1 + pred2 + x2star')
        fit.anova = stats.anova(fit)
        
    

    
#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    try:
        print '===================================================='
        print "begin at " + getCurTime()

        #r = ro.r
        stats = importr('stats')
        base = importr('base')

        data = ro.vectors.DataFrame.from_csvfile('C:/_DATA/migration_census_2000/3million_xi/smoothed_migration_flows_3000000_reduced.csv', sep=',')
        dist = data.rx2('distance')
        flow = data.rx2('flowvale')
        lndist = base.log(distance)
        lnflow = base.log(flow)
        ro.globalenv["dist"] = dist
        ro.globalenv["flow"] = flow
        ro.globalenv["lndist"] = lndist
        ro.globalenv["lnflow"] = lnflow

        x2star = 

        mylm = stats.lm("flow ~ lndist")
        #ro.globalenv["mylm"] = mylm.rx('model')
        
        prd = stats.predict(mylm, interval='prediction')
        prd = np.array(prd)
        print prd

        

        #ctl = FloatVector([4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14])
        #trt = FloatVector([4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69])
        #group = base.gl(2, 10, 20, labels = ["Ctl","Trt"])
        #weight = ctl + trt

        #ro.globalenv["weight"] = weight
        #ro.globalenv["group"] = group
        #ro.globalenv["trt"] = trt
        #mylm = stats.lm("weight ~ trt")
    #print(stats.anova(lm_D9))
    #print base.summary(mylm)
    

    #pi = ro.r['pi']
    #print pi
    except:
        raise
    